<script setup lang="ts">
import { http } from '@/utils/http';
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';
import base64ToBlob from 'b64-to-blob'

// 0. 获取用户数据
const profile = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async () => {
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
  const res = await http.get<MkResponse<ProfileInfo>>('/member/profile')
  profile.value = res.data.result
  closeToast()

  // 给当前日期赋值
  birthday.value = profile.value.birthday.split('-')


  // 设置当前职业
  selectedValues.value.push(profile.value.profession)
})

// 1. 头像处理
const actions = [{ name: '拍照' }, { name: '相册' }]
const showAvatarSheet = ref(false)
const onSelect = async (action: ActionSheetAction, index: number) => {
  if (index === 0) {
    // TODO: 拍照
    uploadAvatar(await mk.pickerCamera())
  } else if (index === 1) {
    // TODO: 相册
    uploadAvatar(await mk.pickerPhoto())
  }
}

const uploadAvatar = async (str: string) => {
  try {
    showLoadingToast({ message: '正在上传中...', duration: 0, forbidClick: true })
    showAvatarSheet.value = false
    // 1. 把base64编码转成File
    const file = base64ToBlob(str, 'image/jpeg')
    // 2. 创建FormData对象, 添加file
    const fd = new FormData()
    fd.append('file', file, Date.now() + '.jpeg')
    // 3. 调用上传图片接口
    const res = await http.post<MkResponse<{ avatar: string }>>('/member/profile/avatar', fd)
    // 4. 得到结果后, 更新数据(h5侧和原生侧)
    profile.value.avatar = res.data.result.avatar
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
  } catch (error) {
    console.log(error);
    showToast({ message: '更新头像失败' })
  } finally {
    showAvatarSheet.value = false
    closeToast()
  }
}


// 2. 出生日期
const showBirthdayPopup = ref(false)
const onChangeBirthday = (data: { selectedValues: string[] }) => {
  profile.value.birthday = data.selectedValues.join('-')
  showBirthdayPopup.value = false
}

// 默认值: ['', '', '']
const date = new Date()
const birthday = ref([date.getFullYear().toString(), String(date.getMonth() + 1), date.getDate().toString()])




// 3. 省市区
interface Location {
  selectedValues: string[]
}
const showLocationPopup = ref(false)
const areaColumns = ref<AreaColumns>({} as AreaColumns)
onMounted(async () => {
  const res = await mk.getAreaColumns()
  areaColumns.value = res
})
const onSelectedLocation = (obj: Location) => {
  profile.value.provinceCode = Number(obj.selectedValues[0])
  profile.value.cityCode = Number(obj.selectedValues[1])
  profile.value.countyCode = Number(obj.selectedValues[2])

  const province = areaColumns.value.province_list[Number(obj.selectedValues[0])]
  const city = areaColumns.value.city_list[Number(obj.selectedValues[1])]
  const county = areaColumns.value.county_list[Number(obj.selectedValues[2])]

  profile.value.fullLocation = `${province} ${city} ${county}`

  showLocationPopup.value = false
}

// 4. 职业
const selectedValues = ref<string[]>([])
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
  // console.log(data.selectedValues)
  profile.value.profession = data.selectedValues[0]
  showProfessionPopup.value = false
}

// 5. 提交
const isLoading = ref(false)
const onSubmit = async () => {
  try {
    isLoading.value = true
    await http.put('/member/profile', profile.value)
    isLoading.value = false

    // 修改原生侧的昵称
    const user = mk.queryUser()
    user.nickname = profile.value.nickname
    mk.updateUser(user)

    showToast({ message: '修改成功~' })
  } catch (error) {
    console.log(error)
  }

}


</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar"
        @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn" @click="showAvatarSheet = true">
        <span>修改头像</span>
      </div>
    </div>
    <van-action-sheet cancel-text="取消" v-model:show="showAvatarSheet" :actions="actions" @select="onSelect"
      @cancel="showAvatarSheet = false" style="padding-bottom: 40px;" />
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field v-model="profile.account" label="账号" readonly></van-field>
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>


      <van-field v-model="profile.birthday" label="生日" readonly placeholder="请选择日期"
        @click="showBirthdayPopup = true"></van-field>
      <van-popup position="bottom" v-model:show="showBirthdayPopup">
        <van-date-picker v-model="birthday" title="选择日期" @cancel="showBirthdayPopup = false" @confirm="onChangeBirthday"
          :min-date="new Date(1949, 10, 1)" />
      </van-popup>



      <van-field v-model="profile.fullLocation" label="所在地" readonly placeholder="请选择所在地"
        @click="showLocationPopup = true"></van-field>
      <van-popup position="bottom" v-model:show="showLocationPopup">
        <van-area title="选择省市区" :area-list="areaColumns" @cancel="showLocationPopup = false"
          @confirm="onSelectedLocation" />
      </van-popup>


      <van-field v-model="profile.profession" label="职业" readonly placeholder="请选择职业"
        @click="showProfessionPopup = true"></van-field>
      <van-popup position="bottom" v-model:show="showProfessionPopup">
        <van-picker v-model="selectedValues" title="选择职业" :columns="columns" @confirm="onChangeProfession"
          @cancel="showProfessionPopup = false" />
      </van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button :loading="isLoading" round block type="primary" @click="onSubmit">
        保存资料
      </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>